<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2018 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: http://www.dsxcms.com
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2018/5/31
 * Time: 下午4:30
 */

use App\Models\Cart;
use App\Models\Item;
use App\Models\Shop;

/**
 * @param $shop_id
 * @return string
 */
function shop_url($shop_id) {
    return action('Shop\ViewShopController@index', ['shop_id'=>$shop_id]);
}

/**
 * @param $itemid
 * @return string
 */
function item_url($itemid) {
    return action('Item\DetailController@index', ['itemid'=>$itemid]);
}

/**
 * @param $catid
 * @return string
 */
function item_catlog_url($catid) {
    return action('Item\SearchController@index', ['catid'=>$catid]);
}

/**
 * @param array $params
 * @return string
 */
function item_search_url($params = []) {
    return action('Item\SearchController@index', $params);
}

/**
 * @return string
 */
function createItemSn(){
    return time().rand(100,999).rand(100,999);
}

/**
 * 生成交易流水号
 * @return string
 */
function createTradeNo(){
    return date('YmdHis').rand(100,999).rand(100,999);
}

/**
 * 生成订单号
 * @param string $prefix
 * @return string
 */
function createOrderNo($prefix='6'){
    return $prefix.time().substr(microtime(), 2,6).rand(0,9);
}

/**
 * @return string
 */
function createReundNo(){
    return '1'.time().rand(10,99).rand(100,999);
}

/**
 * @param $uid
 * @param $itemid
 * @param $quantity
 * @return Cart|\Illuminate\Database\Eloquent\Model|int
 */
function addToCart ($uid, $itemid, $quantity) {

    if (Cart::where(['uid'=>$uid, 'itemid'=>$itemid])->exists()) {
        return Cart::where(['uid'=>$uid, 'itemid'=>$itemid])->increment('quantity', $quantity);
    } else {
        $item = Item::with('shop')->find($itemid);
        return Cart::create([
            'uid'=>$uid,
            'shop_id'=>$item->shop->shop_id,
            'shop_name'=>$item->shop->shop_name,
            'itemid'=>$item->itemid,
            'title'=>$item->title,
            'quantity'=>$quantity,
            'price'=>$item->price,
            'thumb'=>$item->thumb,
            'image'=>$item->image,
            'sku_id'=>0,
            'sku_name'=>'',
            'created_at'=>time(),
            'updated_at'=>time()
        ]);
    }
}

function formatCount($count) {
    if ($count > 10000) {
        return round($count/10000, 2).'万';
    } else {
        return $count;
    }
}
